<?php
/*
 module:		红娘管理
 create_time:	2022-03-04 16:27:06
 author:		
 contact:		
*/

namespace app\backend\controller;

use app\backend\service\ZhMatchmakerAddinfoService;
use app\backend\model\ZhMatchmakerAddinfo as ZhMatchmakerAddinfoModel;
use app\backend\model\Member as MemberModel;
use ZipArchive;
class ZhMatchmakerAddinfo extends Admin
{
    /*首页数据列表*/
    function index()
    {
        if (!$this->request->isAjax()) {
            return view('index');
        } else {
            $limit           = $this->request->post('limit', 20, 'intval');
            $offset          = $this->request->post('offset', 0, 'intval');
            $where['m.phone']   = $this->request->param('phone', '', 'serach_in');
            $where['a.status'] = $this->request->param('status', '', 'serach_in');
            $page = floor($offset / $limit) + 1;
            $res  = ZhMatchmakerAddinfoService::indexList(formatWhere($where), $limit, $page);
            return json($res);
        }
    }

    /*修改*/
    function update()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id', '', 'serach_in');
            if (!$id) $this->error('参数错误');
            $this->view->assign('info', checkData(ZhMatchmakerAddinfoModel::find($id)));
            return view('update');
        } else {
            $postField = 'content,photos,matchmaker_id,status,id';
            $data      = $this->request->only(explode(',', $postField), 'post', null);
            $data["photos"]=json_encode($data["photos"]);
            $res = ZhMatchmakerAddinfoService::update($data);
            return json(['status' => '00', 'msg' => '修改成功']);
        }
    }

    /**
     * @return \think\response\Json|\think\response\View
     * @author  lwx
     */
    function add()
    {
        if (!$this->request->isPost()) {
            return view('add');
        } else {
            $postField = 'content,photos,matchmaker_id,status';
            $data               = $this->request->only(explode(',', $postField), 'post', null);
            $data['createtime'] = time();
            $data['wxapp_id'] = session('backend.wxapp_id');
            $data["photos"]=json_encode($data["photos"]);
            $res                = ZhMatchmakerAddinfoModel::create($data);
            return json(['status' => '00', 'msg' => '添加成功']);
        }
    }
    //下载图片
    function upload(){
        $id = $this->request->get('id', '', 'serach_in');
        $info=ZhMatchmakerAddinfoModel::find($id);
        if(!$info){
          //  $this->error('数据不存在或已被删除');exit();
        }else{
            $imageUrls=json_decode(htmlspecialchars_decode($info["photos"]));
            if(count($imageUrls)>0){
                //文件路径
                $this->downloadImagesAsZip($imageUrls);
            }
            $this->success('下载成功');
          /*  // 开始时间
            $yasuotusttime=microtime(true);
            $imgcount=0;
            // 循环保存图片信息
            foreach ($imageUrls as $fileurl){
                echo "进行下载".$fileurl;
                $this->downimg($fileurl,$fileurl,$imgcount);
            }*/
           // return json(['status' => '00', 'msg' => '下载成功']);
        }
    }
    //根据图片地址生成压缩包并下载
    function downloadImagesAsZip($imageUrls, $zipFileName = 'images.zip') {

        // 创建一个临时目录来存储图片
        $tempDir = sys_get_temp_dir() . '/ad_info_images' ;
        if (!mkdir($tempDir) && !is_dir($tempDir)) {
            throw new RuntimeException(sprintf('Directory "%s" was not created', $tempDir));
        }
        // 下载图片到临时目录
        foreach ($imageUrls as $url) {
            $imageContents = file_get_contents($url);
            if ($imageContents === FALSE) {
                echo "Failed to download image: $url";exit();
               // throw new RuntimeException("Failed to download image: $url");
            }
            $imageName = basename($url);
            file_put_contents("$tempDir/$imageName", $imageContents);
        }
        // 创建一个ZIP文件
        $zip = new ZipArchive();
        $zipFilePath = "$tempDir/$zipFileName";
        if ($zip->open($zipFilePath, ZipArchive::CREATE) !== TRUE) {
            echo "Cannot open".$zipFilePath;exit();
        //    throw new RuntimeException("Cannot open <$zipFilePath>\n");
        }
        // 将图片添加到ZIP文件中
        $files = scandir($tempDir);
        foreach ($files as $file) {
            if ($file !== '.' && $file !== '..' && is_file("$tempDir/$file")) {
                $result=$zip->addFile("$tempDir/$file", $file);
            }
        }
        $zip->close();

        // 设置头信息以下载ZIP文件
        header('Content-Type: application/zip');
        header("Content-Disposition: attachment; filename=$zipFileName");
        header('Content-Length: ' . filesize($zipFilePath));
        readfile($zipFilePath);
        // 清理临时文件和目录
        array_map('unlink', glob("$tempDir/*.*"));
        rmdir($tempDir);
    }
    // 下载文件
    function downimg($fileurl,$filename){

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$fileurl);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data = curl_exec($ch);
        $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($code!=200){
            return;
        }
        $file = fopen($filename,"a");
        fwrite($file,$data); //写入文件
        fclose($file);

    }


    /*删除*/
    function delete()
    {
        $idx = $this->request->post('id', '', 'serach_in');
        if (!$idx) $this->error('参数错误');
        try {
            ZhMatchmakerAddinfoModel::destroy(['id' => explode(',', $idx)], true);
        } catch (\Exception $e) {
            abort(config('my.error_log_code'), $e->getMessage());
        }
        return json(['status' => '00', 'msg' => '操作成功']);
    }

    /*查看详情*/
    function view()
    {
        $id = $this->request->get('id', '', 'serach_in');
        if (!$id) $this->error('参数错误');
        $info=ZhMatchmakerAddinfoModel::find($id);
        $info["photos"]=json_decode($info["photos"]);
        $this->view->assign('info', $info);
        return view('view');
    }

}

